package com.rw.coco.data.data.mapper;

import com.rw.coco.api.data.model.CardModel;
import com.rw.coco.api.data.persistence.simple.SimpleCardMapper;
import com.rw.coco.data.data.bean.FileCardModel;
import com.rw.coco.data.data.util.BeanUtil;
import com.rw.tool.util.io.FileIOUtil;
import com.rw.tool.util.io.file.BeanFile;
import com.rw.tool.util.json.JsonUtil;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class FileCardMapper extends SimpleCardMapper {
    private static final String CARD_PATH = "\\card\\";

    private final BeanFile<FileCardModel> beanFile;

    public FileCardMapper(String workPath) {
        File file = new File(workPath, CARD_PATH);
        FileIOUtil.mkDirs(file);
        this.beanFile = new BeanFile<>(file, FileCardModel.class);
    }

    private FileCardModel convert(CardModel data) {
        return JsonUtil.convertObj(data, FileCardModel.class);
    }

    private CardModel reconvert(FileCardModel data) {
        return JsonUtil.convertObj(data, CardModel.class);
    }

    private FileCardModel removeId(FileCardModel data) {
        return BeanUtil.removeIdProp(data, FileCardModel.class);
    }

    @Override
    public void insert(CardModel data) {
        beanFile.insert(convert(data));
    }

    @Override
    public void insertAll(Collection<CardModel> dataList) {
        List<FileCardModel> modelList = dataList.stream()
                .map(this::convert)
                .collect(Collectors.toList());

        beanFile.insertAll(modelList);
    }

    @Override
    public void delete(Serializable id) {
        beanFile.deleteById(id);
    }

    @Override
    public void deleteAll(CardModel data) {
        beanFile.delete(BeanUtil.getQueryWrapper(data));
    }

    @Override
    public void update(CardModel data) {
        FileCardModel cardModel = convert(data);
        beanFile.update(BeanUtil.getIdWrapper(cardModel), removeId(cardModel));
    }

    @Override
    public CardModel selectOne(Serializable id) {
        return beanFile.selectById(id);
    }

    @Override
    public List<CardModel> selectList(CardModel data) {
        return beanFile.selectList(BeanUtil.getQueryWrapper(data))
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }

    @Override
    public List<CardModel> selectList(Collection<? extends Serializable> id) {
        return beanFile.selectList(id)
                .stream()
                .map(this::reconvert)
                .collect(Collectors.toList());
    }
}
